﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using cecbData;
using System.Collections.ObjectModel;
using cecbClasses.Data_Adapters;
using System.Text.RegularExpressions;

namespace CECB
{
    /// <summary>
    /// Interaction logic for V_FillMatrix_Window.xaml
    /// </summary>
    public partial class V_FillMatrix_Window : Window
    {

        DSSEntities dataContext;
        bool IsProjectSelected = false;
        Projects proj;
        String ProjId = "";
        String _activityRef = null;
        String _impactRef = null;

        public V_FillMatrix_Window()
        {
            InitializeComponent();
            dataContext = new DSSEntities();
            ProjectAutocompleteTextBox.IsEnabled = false;
            ProjectAutocompleteTextBox.ItemsSource = new Func_Projects().getAllProjects();
        }

        #region Fill Impacts

        public void fillImpacts() {
            //-------------------------------------------------------------------------------

            IQueryable<Components> qComponents = (from c in dataContext.ProjectImpacts
                                                  join b in dataContext.Impacts on c.impt_reference equals b.impt_reference
                                                  join d in dataContext.Components on b.impt_component equals d.cmpt_reference
                                                  where c.proj_reference == ProjId
                                                  orderby b.impt_component
                                                  select d).Distinct();

            int y = 0;
            foreach (Components com in qComponents)
            {

                treeView1.Items.Add(new TreeViewItem() { Header = com.cmpt_name });

                //========================================get  impact
                IQueryable<Impacts> qImpacts = from c in dataContext.ProjectImpacts
                                               join b in dataContext.Impacts on c.impt_reference equals b.impt_reference

                                               where c.proj_reference == ProjId && b.impt_component == com.cmpt_reference
                                               orderby b.impt_component
                                               select b;
                //===================================================

                int x = 1;
                foreach (Impacts imp in qImpacts)
                {

                    ((TreeViewItem)treeView1.Items[y]).Items.Add(new TreeViewItem()
                    {
                        Header = " " + x + ". " + imp.impt_name,
                        Foreground = Brushes.Maroon,
                        //  Background = Brushes.WhiteSmoke,
                        BorderBrush = Brushes.Black,
                        Cursor = Cursors.Hand,
                        FontSize = 14,
                        Height = 20,
                        DisplayMemberPath = imp.impt_reference
                    });
                    x++;
                }
                y++;

            }
        }

        #endregion

        #region Fill Activity

        public void fillActivities() {

            //-------------------------------------------------------------------------------

            IQueryable<Activities> qComponents = (from c in dataContext.ProjectActivities
                                                  join b in dataContext.Activities on c.actv_reference equals b.actv_reference

                                                  where c.proj_reference == ProjId
                                                   orderby b.actv_phase
                                                  select b).GroupBy(b => b.actv_phase).Select(x => x.FirstOrDefault());

            int y = 0;
            foreach (Activities act in qComponents)
            {

                treeView2.Items.Add(new TreeViewItem() { Header = act.actv_phase });

                //========================================get  impact
                IQueryable<Activities> qImpacts = from c in dataContext.ProjectActivities
                                               join b in dataContext.Activities on c.actv_reference equals b.actv_reference

                                                  where c.proj_reference == ProjId && b.actv_phase == act.actv_phase
                                               select b;
                //===================================================

                int x = 1;
                foreach (Activities imp in qImpacts)
                {

                    ((TreeViewItem)treeView2.Items[y]).Items.Add(new TreeViewItem()
                    {
                        Header = "   "+ imp.actv_name,
                        Foreground = Brushes.Maroon,
                       // Background = Brushes.WhiteSmoke,
                        BorderBrush = Brushes.Black,
                        Cursor = Cursors.Hand,
                        FontSize = 14,
                        Height = 20,
                        DisplayMemberPath = imp.actv_reference
                        
                    });
                    x++;
                }
                y++;

            }
        
        }


        #endregion

        public bool IsDataAvailabel(String imp , String act , String pid) {
            bool ok = false;

            var quary = from c in dataContext.LeopoldMatrixValues
                        where c.proj_reference == pid &&
                                c.actv_reference == act &&
                                c.impt_reference == imp &&
                                c.mtrx_magnitude.HasValue &&
                                c.mtrx_importance.HasValue
                        select c;

            if (quary.ToList().Count > 0)
                ok = true;

            return ok;
        }

        public void clearTreeBackGround(TreeView tvi) {

            try
            {
                foreach (TreeViewItem x in ((TreeViewItem)tvi.Items[0]).Items)
                {
                    x.Background = Brushes.Transparent;
                }
                foreach (TreeViewItem x in ((TreeViewItem)tvi.Items[1]).Items)
                {
                    x.Background = Brushes.Transparent;
                }
                foreach (TreeViewItem x in ((TreeViewItem)tvi.Items[2]).Items)
                {
                    x.Background = Brushes.Transparent;
                }
            }
            catch (Exception)
            {
                
               
            }
        }

        private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
          TreeViewItem tvi =  (TreeViewItem) treeView1.SelectedItem;
            labelImpact.Content = tvi.Header.ToString();

             _impactRef = tvi.DisplayMemberPath.ToString();
             clearTreeBackGround(treeView2);
        }
        private void treeView2_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            buttonConfirm.IsEnabled = true;
            buttonAddMatrix.IsEnabled = false;
            TreeViewItem tvi = (TreeViewItem)treeView2.SelectedItem;
            labelActivity.Content = tvi.Header.ToString();
            _activityRef = tvi.DisplayMemberPath.ToString();
            if (IsDataAvailabel(_impactRef, _activityRef, ProjId)) {
                tvi.Background = Brushes.Green;
            
            }
               
        }
 

        private void ProjectTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ComboboxSelectMatrix.SelectedIndex > -1)
                {
                    IsProjectSelected = true;
                    treeView1.Items.Clear();
                    treeView2.Items.Clear();
                    proj = (Projects)ProjectAutocompleteTextBox.SelectedItem;
                    ProjId = proj.proj_reference;

                    fillImpacts();
                    fillActivities();

                    if (ComboboxSelectMatrix.SelectedIndex == 1)
                    {

                        try
                        {
                            var range = (from c in dataContext.ProjectCriteria
                                         where c.proj_reference == ProjId &&
                                                c.proj_matrix == "Leopold"
                                         select c.crt_range).FirstOrDefault();

                       // foreach (var x in range)
                       // {
                            Iv.Content = range.ToString();
                            Mv.Content = range.ToString();

                      //  }
                        }
                        catch (Exception)
                        {
                            
                          
                        }
                    }
                    else {

                        //try
                        //{
                        //     var range = (from c in dataContext.ProjectCriteria
                        //             where c.proj_reference == ProjId &&
                        //                    c.proj_matrix == "Simple"
                        //             select c.crt_range).FirstOrDefault();

                        //foreach (var x in range)
                        //{
                        //    Iv.Content = x.ToString();
                        //}
                        //}
                        //catch (Exception)
                        //{
                            
                           
                        //}
                    
                    }

                }
                else
                {
                   // ProjectAutocompleteTextBox.SelectedItem = null;

                    MessageBox.Show("Select a matrix type!", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception)
            {


            }
        }

        private void buttonConfirm_Click(object sender, RoutedEventArgs e)
        {
            if (IsProjectSelected)
            {
                if (labelImpact.Content.ToString() == "")
                {
                    MessageBox.Show("Enter impact name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (labelActivity.Content.ToString() == "")
                {
                    MessageBox.Show("Enter activity name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    buttonAddMatrix.IsEnabled = true;
                    stackPanelActivity.Background = new SolidColorBrush(Colors.Green);
                    stackPanelImpact.Background = new SolidColorBrush(Colors.Green);
                    textBoxImportance.IsEnabled = true;
                    textBoxMagnitude.IsEnabled = true;
                }
            }
            else
                MessageBox.Show("Select a project", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void textBoxMagnitude_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        private void textBoxMagnitude_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void textBoxImportance_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

      

        private void buttonAddMatrix_Click(object sender, RoutedEventArgs e)
        {
            String impName = labelImpact.Content.ToString();
            String actName = labelActivity.Content.ToString();
            String ival = textBoxMagnitude.Text.ToString();
            String mval = textBoxImportance.Text.ToString();

            if (labelImpact.Content.ToString() == "")
            {
                MessageBox.Show("Enter impact name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else if (labelActivity.Content.ToString() == "")
            {
                MessageBox.Show("Enter activity name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
             
            else if (true)
            {
                if (ComboboxSelectMatrix.SelectedIndex == 1)
                {

                    Dss.Methods.FillMatrix fillmx = new Dss.Methods.FillMatrix();
                    if (fillmx.InsertValues(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxMagnitude.Text, textBoxImportance.Text))
                    {
                        MessageBox.Show("Inserted Leopold Matrix Value", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                       
                        buttonConfirm.IsEnabled = false;
                    }
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Values are already in database! Do you want to update?", "Message", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            // fillmx.UpdateValues(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxMagnitude.Text, textBoxImportance.Text);
                        }

                    }
                }

                else if (ComboboxSelectMatrix.SelectedIndex == 0)
                {


                    if (new cecbClasses.Data_Adapters.SimpleMatrixCalculation().InsertValuesToSimpleMatrix(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxImportance.Text))
                    {
                        MessageBox.Show("Inserted Simple Matrix Value", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                         
                        buttonConfirm.IsEnabled = false;
                    }
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Values are already in database! Do you want to update?", "Message", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            // fillmx.UpdateValues(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxMagnitude.Text, textBoxImportance.Text);
                        }

                    }

                }

                textBoxImportance.Text = "";
                textBoxMagnitude.Text = "";
                textBoxImportance.IsEnabled = false;
                textBoxMagnitude.IsEnabled = false;
                stackPanelActivity.Background = new SolidColorBrush(Colors.Red);
                stackPanelImpact.Background = new SolidColorBrush(Colors.Red);

            }
        }

        private void textBoxMagnitude_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void ProjectAutocompleteTextBox_TextChanged(object sender, RoutedEventArgs e)
        {
            IsProjectSelected = false;
            
        }

        private void ComboboxSelectMatrix_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ComboboxSelectMatrix.SelectedIndex == 0)
            {
                lblimp.Visibility = System.Windows.Visibility.Hidden;
                lblmag.Visibility = System.Windows.Visibility.Visible;
                textBoxMagnitude.Visibility = System.Windows.Visibility.Hidden;
                lblmag.Content = "Importance Value";

            }
            else if (ComboboxSelectMatrix.SelectedIndex == 1)
            {

                lblimp.Visibility = System.Windows.Visibility.Visible;
                lblmag.Visibility = System.Windows.Visibility.Visible;
                textBoxImportance.Visibility = System.Windows.Visibility.Visible;
                textBoxMagnitude.Visibility = System.Windows.Visibility.Visible;
                lblmag.Content = "Magnitude Value";
            }

            ProjectAutocompleteTextBox.IsEnabled = true;
        }

        private void textBoxMagnitude_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        

    }
     
}
